package com.example.demo.design.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author: liull
 * @Description: 负载均衡器LoadBalancer：单例类，真实环境下该类将非常复杂，包括大量初始化的工作
 * @Date: Created in 9:55 2021/4/9
 * @Modified By:
 */
public class LoadBalancer {

    private static volatile LoadBalancer INSTANCE = null;

    private List<String> serverList = null;

    private LoadBalancer() {
        serverList = new ArrayList<>();
    }

    public static LoadBalancer getLoadBalancer() {
        if (INSTANCE == null) {
            synchronized (LoadBalancer.class) {
                if (INSTANCE == null) {
                    INSTANCE = new LoadBalancer();
                }
            }
        }
        return INSTANCE;
    }

    public void addServer(String server) {
        serverList.add(server);
    }

    public void removeServer(String server) {
        serverList.remove(server);
    }

    public String getServer() {
        return serverList.get(new Random().nextInt(serverList.size()));
    }

}
